package com.softdong.home.config;


import com.softdong.home.properties.ApiInfoProperties;
import com.softdong.home.properties.ContactProperties;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2//开启Swagger
public class SwaggerConfig {

    @Bean
    @ConfigurationProperties(prefix = "swagger")
    public ApiInfoProperties apiInfoProperties() {
        return new ApiInfoProperties();
    }

    @Bean
    @ConfigurationProperties(prefix = "swagger.contact")
    public ContactProperties contactProperties(){
        return new ContactProperties();
    }

    @Bean
    public Docket createRestApi(ApiInfoProperties apiInfoProperties,ContactProperties contactProperties) {
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        tokenPar.name("sessionKey").description("会话id").modelRef(new ModelRef("string")).parameterType("header")
            .required(false).build();
        pars.add(tokenPar.build());

        return new Docket(DocumentationType.SWAGGER_2)
                .globalOperationParameters(pars)
                .apiInfo(apiInfo(apiInfoProperties,contactProperties))
                .select()
                .apis(RequestHandlerSelectors.basePackage(apiInfoProperties.getBasePackage()))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo(ApiInfoProperties apiInfoProperties,ContactProperties contactProperties) {
        Contact contact = new Contact(contactProperties.getName(),contactProperties.getUrl(),contactProperties.getEmail());
        return new ApiInfoBuilder()
                .title(apiInfoProperties.getTitle())
                .description(apiInfoProperties.getDescription())
                .termsOfServiceUrl(apiInfoProperties.getTermsOfServiceUrl())
                .contact(contact)
                .version(apiInfoProperties.getVersion())
                .build();
    }
}
